Bingo, Computer Graphics & Game Developer
1.在Lua中完成全局函数的绑定时 要注意 调用这个函数需要放在pcall之后 因为在这之前 栈一直是空的
而pcall的作用就是讲lua文件编译 并将全局变量(函数是闭包也就是一个变量)压栈 这时候对整个儿自定义的方法进行的操作才是有意义的
不然会得到unprotected error in call to Lua API (attempt to call a nil value)
的错误
2.但凡是对全局变量进行的预先处理操作 可以在lua_pcall之前完成 而那些需要使用到全局变量(如返回值 闭包等变量)的一定要等到pcall完成 也就是编译压栈全局变量完成之后才能进行 不然也会报unprotected error in call to Lua API (attempt to call a nil value)
的错误
比如 尝试返回三个值
– local表示存在于栈中的变量 而不是存在与table中的全局变量
local temp = {9, "hehehe"} return temp,9,1
在C程序中
std::stringstream strBuffer; while(lua_gettop(luaState)) { strBuffer.str(std::string()); strBuffer << "lua returned a "; int index = lua_gettop(luaState); switch(lua_type(luaState, index)) { case LUA_TNUMBER: strBuffer << "number" << lua_tonumber(luaState, index); break; case LUA_TTABLE: strBuffer << "table"; break; case LUA_TSTRING: strBuffer << "string" << lua_tostring(luaState, index); break; case LUA_TBOOLEAN: strBuffer << "boolean" << lua_toboolean(luaState, index); break; default: strBuffer << "unknow type"; break; } strBuffer << "\n"; lua_pop(luaState, 1); cout << strBuffer.str() << endl; }
期望能够解析出每个返回值的类型信息
这一步的操作就应该放在pcall之后 不然会发现操作的栈都是空的 那么就都是对nil进行的非法操作